package info.batcloud.fanli.core.item.collection;

import com.alibaba.fastjson.JSON;
import com.ctospace.archit.common.pagination.Paging;
import info.batcloud.fanli.core.dto.CommissionItemFetchDTO;
import info.batcloud.fanli.core.entity.ItemSelection;
import info.batcloud.fanli.core.enums.ItemSelectionType;
import info.batcloud.fanli.core.repository.ItemSelectionRepository;
import info.batcloud.fanli.core.service.ChannelCommissionItemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

public abstract class AbstractItemSelectionCollector<T extends Context> implements CommissionItemCollector<T> {

    private static final Logger logger = LoggerFactory.getLogger(CommissionItemCollector.class);

    public static final Map<ItemSelectionType, AbstractItemSelectionCollector> COLLECTOR_MAP = new HashMap<>();

    @Inject
    private ItemSelectionRepository itemSelectionRepository;

    @Inject
    private ChannelCommissionItemService channelCommissionItemService;

    @PostConstruct
    public void init() {
        COLLECTOR_MAP.put(this.getItemSelectionType(), this);
    }

    public CollectResult collect(long itemSelectionId, Consumer<Paging<CommissionItemFetchDTO>> pagingConsumer) {
        ItemSelection selection = itemSelectionRepository.findOne(itemSelectionId);
        logger.info("开始抓取选品库：" + selection.getName());
        T context = JSON.parseObject(selection.getConfig(), getContextType());
        context.setRecommend(selection.isRecommend());
        context.setMaxPage(selection.getMaxPage());
        if (selection.getShopcat() != null) {
            context.setShopcatId(selection.getShopcat().getId());
        }
        if (selection.getChannel() != null) {
            context.setChannelId(selection.getChannel().getId());
        }
        context.setClearChannelItem(selection.isClearChannelItem());
        if(context.getChannelId() != null && context.isClearChannelItem()) {
            channelCommissionItemService.deleteByChannelId(context.getChannelId());
        }
        CollectResult result;
        try {
            result = this.collect(context, pagingConsumer);
            if (result.isSuccess()) {
                logger.info("完成抓取选品库：" + selection.getName() + ", 共抓取数量：" + result.getTotalNum());
            } else {
                logger.info("选品库抓取错误：" + selection.getName() + ", 原因：" + result.getErrMsg());
            }
        } catch (Exception e) {
            result = new CollectResult();
            result.setSuccess(false);
            result.setErrMsg(e.getLocalizedMessage());
            logger.error("抓取出错", e);
        }
        selection.setLastFetchTime(new Date());
        selection.setLastSyncTime(new Date());
        selection.setLastFetchNum(result.getTotalNum());
        if (result.isSuccess()) {
            selection.setErrorMsg(null);
        } else {
            selection.setErrorMsg(result.getErrMsg());
        }
        itemSelectionRepository.save(selection);
        return result;
    }

    abstract ItemSelectionType getItemSelectionType();
}
